/**
 * Copyright (c) 2009, Nathan Bubna
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Manages auto-refreshing of a page or specific elements,
 * to keep data fresh and/or keep a server-side session alive.
 *
 *   $.refresh('keepAlive.do');
 *   $('#notify').refresh('updates.json', 5*60*1000, function(data) {
 *      addNotification(data.latest);
 *   });
 *
 * Both the global and selection methods accept a url, a time in ms (optional),
 * and a handler for the ajax call (optional).  Alternately, you can just pass
 * in an options object.  If the JSON-REST plugin is available, it will use
 * that for all calls unless you specify a different method option.
 * 
 * @version 0.5
 * @name refresh
 * @cat Plugins/Refresh
 * @author Nathan Bubna
 */
;(function ($) {

    var R = $.refresh = $.fn.refresh = function(a, b, c) {
        return R.setup(opts.apply(this, arguments));
    };
    function opts(a, b, c) {
        var r = $.extend({}, R);
        if (typeof a == "string") {
            r.url = a;
            if (b && !$.isFunction(b)) r.time = b; else c = b;
            if (c) r.success = c;
        }
        else $.extend(r, a);
        if (!r.method) r.method = $.rest ? 'Read' : 'ajax';
        if (!r.target) r.target = this ? this : $;
        if (!r.type && !$.rest) r.type = 'GET';
        return r;
    }

    $.extend(R, {
        version: "0.5",
        url: null,
        time: (30*60-2)*1000,//29m58s default
        success: null,
        method: null,
        setup: function(r) {
            if (r.cancel) r.cancel();//clear old
            r.id = setInterval(function() { r.refresh(r); }, r.time);
            r.cancel = function() {
                clearInterval(r.id);
                return r;
            };
            return r;
        },
        refresh: function(r) {
            if (r.lastReturn) delete r.lastReturn;
            r.lastReturn = r.target[r.method](r);
        }
    });

})(jQuery);
